﻿using System;
using Epm.AppLogic.Framework;
using msBsc.Xsd.DataTds;
using System.Data;

namespace msBsc.AppLogic.DataAlc
{
    public class CBizShpScoreSalesLog : CustBizObject
    {
        private CDmShpScoreSalesLog m_CDmShpScoreSalesLog = new CDmShpScoreSalesLog();
        private CDmShpScoreSalesLog oDmShpScoreSalesLog
        {
            get { return m_CDmShpScoreSalesLog; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public CBizShpScoreSalesLog()
            : base()
        {
            this.DataObj = new CDbAccess();
            this.DataObj.Init(this.m_CDmShpScoreSalesLog.SHP_SCORE_SALES_LOG);
            this.TableName = this.DataObj.TableName;
            this.DataObj.KeyField = this.DataObj.Fields["SALES_LOG_ID"]; 
        }

        /// <summary>
        /// 新增记录前的处理
        /// </summary>
        /// <param name="drw">新增数据行</param>
        /// <returns>true/false</returns>
        /// <remarks>
        /// 生成ID值
        /// </remarks>
        protected override bool BeforeRowAdded(DataRow drw)
        {
            if (drw[this.KeyFieldName].ToString().Length < 10)
            {
                drw[this.KeyFieldName] = this.DataObj.NewID();
            }
            if (drw["TRADING_NO"].ToString() == string.Empty)
            {
                drw["TRADING_NO"] = GetNewTradingNo();// msBsc.SvRef.ApplicationConst.Const.GetNewSerialNo("TRADING_NO", System.DateTime.Now.Year.ToString(), 8);
            }
            //drw["BUYER_DEL"] = false;
            //drw["BUYER_RATE_SID"] = "";

            if ((decimal)drw["STL_AMT"] == 0M)
            {
                drw["TRADING_SID"] = "已支付";
            }
            else
            {
                drw["TRADING_SID"] = "待支付";
            }
            return true;
        }

        public string GetNewTradingNo()
        {
            return "00"+msBsc.SvRef.ApplicationConst.Const.GeneratelongId().ToString();
        }

        protected override bool AfterRowAdded(DataRow drw)
        {
            AddTradingLog(drw);
            return true;
        }

        /// <summary>
        /// 记录修改前检验
        /// </summary>
        /// <param name="drw">当前记录</param>
        /// <returns>>校验合法，返回值为true,否则返回false</returns>
        /// <remarks>
        /// ID不允许修改,并把此修改操作记录到BSE_MODIFY_HISTORY表中
        /// </remarks>
        protected override bool BeforeRowModified(DataRow drw)
        {
            //ID不容许修改
            if (drw[this.KeyFieldName].ToString() != drw[this.KeyFieldName, DataRowVersion.Original].ToString())
            {
                Exception e = new Exception(this.TableName + "表的主键" + this.KeyFieldName + "字段不允许被修改");
                throw e;
            } 
            return true;
        }

        protected override bool AfterRowModified(DataRow drw)
        {
            AddTradingLog(drw);
            return true;
        }

        private void AddTradingLog(DataRow drw)
        {
            //店铺台帐增加记录
            if (drw.RowState == DataRowState.Added || drw.RowState == DataRowState.Modified && drw["TRADING_SID", DataRowVersion.Original].ToString() != drw["TRADING_SID"].ToString())
            {
                if (drw["TRADING_SID"].ToString() == "已支付")
                {
                    using (msBsc.AppLogic.DataAlc.CBizShpScoreTradingLog objrad = new CBizShpScoreTradingLog())
                    {
                        objrad.AddTradingLogFromScoreSalse(drw);
                    }
                }
            }
            if (drw.RowState == DataRowState.Added && drw["TRADING_SID"].ToString() == "待支付")
            {
                using (msBsc.AppLogic.DataAlc.CBizShpChargeTradingLog objrad = new CBizShpChargeTradingLog())
                {
                    objrad.AddTradingLogForAddScoreSalse(drw);
                }
            }
        }

        public DataSet SelectByIds(string strIdS)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE  " + this.KeyFieldName + " IN  ('" + strIdS.Replace("'", "").Replace(",", "','") + "')");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public DataSet SelectByTradingNo(string strTradingNo)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE  TRADING_NO ='" + strTradingNo + "'");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public DataSet SelectForFinder(string strPUB_NO, string strTRADING_NO, string strCOMM_USER_NME, string strSALES_TYPE_CID)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE (1=1)"
                + (strPUB_NO == string.Empty ? "" : " AND (PUB_NO='" + strPUB_NO + "')")
                + (strTRADING_NO == string.Empty ? "" : " AND (TRADING_NO='" + strTRADING_NO + "')")
                + (strCOMM_USER_NME == string.Empty ? "" : " AND (COMM_USER_NME='" + strCOMM_USER_NME + "' OR COMM_TENANT_NME='" + strCOMM_USER_NME + "')")
                + (strSALES_TYPE_CID == string.Empty ? "" : " AND (SALES_TYPE_CID='" + strSALES_TYPE_CID + "')")
                + "  ORDER BY INITIAL_DT ASC");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        /// <summary>
        /// 形成销售记录，该记录交易状态为已支付后更新账户积分合计和增加交易日志记录
        /// </summary>
        /// <param name="strSalesType">赠予，购买</param>
        /// <param name="strDealerId"></param>
        /// <param name="iQty"></param>
        public string addSalesScoreLog(string strSalesType, string strDealerId, int iQty)
        {
            if (strSalesType == "" || iQty <= 0)
            {
                return "";
            }
            string strretno = "";
            using (msBsc.AppLogic.DataAlc.CBizShpCommercialTenantInfo objdealer = new CBizShpCommercialTenantInfo())
            {
                DataSet dsShop = objdealer.SelectById(strDealerId);
                if (dsShop.Tables[0].Rows.Count <= 0)
                {
                    throw new Exception("商家信息未找到！");
                }
                //dsShop.Tables[0].Rows[0]["SCORE_QTY"] = (int)dsShop.Tables[0].Rows[0]["SCORE_QTY"] + iQty;
                DataSet dsLog = new CDmShpScoreSalesLog();
                using (msBsc.AppLogic.DataAlc.CBizShpScorePub objpub = new CBizShpScorePub())
                {
                    DataSet ds = objpub.SelectSurplusQty();
                    if (ds.Tables[0].Rows.Count <= 0)
                    {
                        throw new Exception("商城没有发行新的积分前不能进行此操作！");
                    }

                    DataRow drnew = dsLog.Tables[0].NewRow();
                    drnew["SALES_LOG_ID"] = this.DataObj.NewID();
                    //drnew["PUB_NO"] = ds.Tables[0].Rows[i]["PUB_NO"];
                    drnew["TRADING_NO"] = GetNewTradingNo();// msBsc.SvRef.ApplicationConst.Const.GetNewSerialNo("TRADING_NO", System.DateTime.Now.Year.ToString(), 8);
                    drnew["COMM_TENANT_ID"] = dsShop.Tables[0].Rows[0]["COMM_TENANT_ID"];
                    drnew["COMM_TENANT_NME"] = dsShop.Tables[0].Rows[0]["COMM_TENANT_NME"];
                    drnew["COMM_USER_NME"] = dsShop.Tables[0].Rows[0]["USER_NME"];
                    drnew["TRADING_SID"] = "待支付";
                    drnew["SALES_TYPE_CID"] = strSalesType;
                    drnew["SALES_QTY"] = iQty;
                    drnew["SALES_PRICE"] = msBsc.SvRef.SysConst.decScoreSalesPrice();
                    drnew["SALES_AMT"] = msBsc.SvRef.SysConst.decScoreSalesPrice() * iQty;
                    if (strSalesType == "赠予")
                    {
                        drnew["DISCOUNT_AMT"] = drnew["SALES_AMT"];
                        drnew["STL_AMT"] = 0M;
                    }
                    else
                    {
                        drnew["DISCOUNT_AMT"] = 0M;
                        drnew["STL_AMT"] = drnew["SALES_AMT"];
                    }
                    dsLog.Tables[0].Rows.Add(drnew);


                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (iQty <= 0)
                        {
                            break;
                        }
                        int iSalesQty = 0;
                        if ((int)ds.Tables[0].Rows[i]["SURPLUS_QTY"] > iQty)
                        {
                            iSalesQty = iQty;
                        }
                        else
                        {
                            iSalesQty = (int)ds.Tables[0].Rows[i]["SURPLUS_QTY"];
                        }
                        //if (iSalesQty <= 0)
                        //{
                        //    throw new Exception("当前交易的积分数据超出已发行的积分数据，请重新选择！");
                        //}

                        ds.Tables[0].Rows[i]["SURPLUS_QTY"] = (int)ds.Tables[0].Rows[i]["SURPLUS_QTY"] - iSalesQty;
                        ds.Tables[0].Rows[i]["SALES_QTY"] = (int)ds.Tables[0].Rows[i]["SALES_QTY"] + iSalesQty;
                        if (strSalesType == "赠予")
                        {
                            ds.Tables[0].Rows[i]["STL_AMT"] = (decimal)ds.Tables[0].Rows[i]["STL_AMT"] + 0M;
                            ds.Tables[0].Rows[i]["DISCOUNT_AMT"] = (decimal)ds.Tables[0].Rows[i]["DISCOUNT_AMT"] + msBsc.SvRef.SysConst.decScoreSalesPrice() * iSalesQty;
                            ds.Tables[0].Rows[i]["SALES_AMT"] = (decimal)ds.Tables[0].Rows[i]["SALES_AMT"] + msBsc.SvRef.SysConst.decScoreSalesPrice() * iSalesQty; 
                        }
                        else
                        {
                            ds.Tables[0].Rows[i]["STL_AMT"] = (decimal)ds.Tables[0].Rows[i]["STL_AMT"] + msBsc.SvRef.SysConst.decScoreSalesPrice() * iSalesQty;
                            ds.Tables[0].Rows[i]["DISCOUNT_AMT"] = (decimal)ds.Tables[0].Rows[i]["DISCOUNT_AMT"] + 0M;
                            ds.Tables[0].Rows[i]["SALES_AMT"] = (decimal)ds.Tables[0].Rows[i]["SALES_AMT"] + msBsc.SvRef.SysConst.decScoreSalesPrice() * iSalesQty; 
                        }




                        iQty = iQty - iSalesQty; 
                    }

                    if (iQty > 0)
                    {
                        throw new Exception("当前交易的积分数量、超出已发行的积分数量，请重新输入！");
                    }


                    this.Update(dsLog);
                    objpub.Update(ds);

                }

                //objdealer.Update(dsShop);
            }
            return strretno;
        }


        //public void SetSalesScore(string strRelId,string strRelType, string strTradingType
        //    , int iScoreQty
        //    ,decimal decPrice
        //    ,decimal decAmt
        //    ,string strBuyer
        //    ,string strBuyerDesc
        //    ,string strSeller
        //    ,string strSellerDesc
        //    )
        //{ 
        //    CDbParmCollection parmCollection = new CDbParmCollection();;
        //    parmCollection.Add(new CDbParm("strTradigNo", ParameterDirection.Input, EDbType.String, 36, msBsc.SvRef.ApplicationConst.Const.GetNewSerialNo("TRADING_NO", System.DateTime.Now.Year.ToString(), 8)));
        //    parmCollection.Add(new CDbParm("strTradingId1", ParameterDirection.Input, EDbType.String, 36, this.DataObj.NewID()));
        //    parmCollection.Add(new CDbParm("strTradingId2", ParameterDirection.Input, EDbType.String, 36, this.DataObj.NewID()));
        //    parmCollection.Add(new CDbParm("strOrderId", ParameterDirection.Input, EDbType.String, 36, strOrderId));
        //    parmCollection.Add(new CDbParm("strRelId", ParameterDirection.Input, EDbType.String, 36, strRelId))
        //    parmCollection.Add(new CDbParm("strOrderId", ParameterDirection.Input, EDbType.String, 36, strOrderId));
        //    parmCollection.Add(new CDbParm("strOrderId", ParameterDirection.Input, EDbType.String, 36, strOrderId));
        //    parmCollection.Add(new CDbParm("strOrderId", ParameterDirection.Input, EDbType.String, 36, strOrderId));
        //    parmCollection.Add(new CDbParm("strOrderId", ParameterDirection.Input, EDbType.String, 36, strOrderId));
        //    parmCollection.Add(new CDbParm("strOrderId", ParameterDirection.Input, EDbType.String, 36, strOrderId));
        //    this.DataObj.ExecuteBySP("SHP_SCORE_ADD_TRADING_LOG", parmCollection);
        //}


    }
}
